import axios from "axios";

import config from "@/config";

const TOKEN_INVALID = 'TOKEN认证失败,请重新登录'

const NETWORK_ERROR = '网络请求异常,请稍后重试'

import { Message } from "element-ui";

import router from "@/router";

import storage from "./storage";

const service = axios.create({
    baseURL: config.baseApi,
    timeout: 5000
})


// 添加请求拦截器
service.interceptors.request.use(function (req) {
    let token = storage.getItem('token') || ''
    let headers = req.headers
    if (!headers.Authorization) {
        headers.Authorization = 'Bearer ' + token
    } 
    // 在发送请求之前做些什么
    return req;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
service.interceptors.response.use(function (res) {
    let { code, data } = res.data
    if (code == 200) {
        return data
    } else if (code == 40001) {
        Message.error(TOKEN_INVALID)
        setTimeout(() => {
            router.push('/login')
        }, 1000);
        return Promise.reject(TOKEN_INVALID)
    } else {
        Message.error(NETWORK_ERROR)
        return Promise.reject(NETWORK_ERROR)
    }
    // 对响应数据做点什么
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});



function request (options){
    options.method = options.method || 'get'

    // toLowerCase将请求方式转成小写
    if(options.method.toLowerCase() == 'get'){
        options.params = options.data   //{name : "jack"}
    }

    if(config.env == 'production'){  // 上线
        service.defaults.baseURL = config.baseApi
    }else{ //本地
        service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }

    return service(options)   //axios
}


['get', 'post', 'put', 'delete', 'patch'].forEach((item)=>{
    request[item] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})


export default request